package com.example.cslp.service.Impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.example.cslp.pojo.DTO.CourseDTO;
import com.example.cslp.pojo.entity.Course;
import com.example.cslp.service.ICourseService;
import com.example.cslp.service.IOssService;
import com.example.cslp.util.VideoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author ming
 */

@Slf4j
@Service
public class OssServiceImpl implements IOssService {

    private static final String TEMP_FILEPATH = "tmp/cslp_oss/video_";
    private static final String VIDEO_FILEPATH="cslp/course/video";
    private static final String COVER_FILEPATH="cslp/course/cover";
    private static final String PRE_URL="https://ming-space.oss-cn-chengdu.aliyuncs.com/cslp/course";

    @Autowired
    private ICourseService iCourseService;

    @Override
    @Transactional
    public void upload(MultipartFile multipartFile, CourseDTO courseDTO) throws Exception {
        log.info("开始处理新增课程请求...");
        String accessKeyId ="LTAI5tLjQk61Cm3H9WNvAKUy";
        String accessKeySecret = "T1brfC5ShshVcBtJyqRL5n7BVCTd1W";
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        String bucketName="ming-space";

        //获取文件原始名称
//        String originalFileName=multipartFile.getOriginalFilename();
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix =originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重命名文件
        String fileName= UUID.randomUUID().toString()+suffix;
        String localFile=  TEMP_FILEPATH+fileName;
        // 获取当前类的路径
        String currentClassPath = OssServiceImpl.class.getClassLoader().getResource("").getPath();
        // 构建相对路径
        String relativeFolderPath = ".";
        String absoluteFilePath = currentClassPath + localFile;
        log.debug("absolutePath:{}",absoluteFilePath);
        String videoName=VIDEO_FILEPATH+"/"+fileName;
        log.debug("viedoName:{}",videoName);
        String coverName=null;

        log.debug("正将课程视频存入本地临时文件夹:{}",absoluteFilePath);
        //将课程视频存入本地临时文件夹
        try {
            String dirPath = absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf("/"));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
                return;
            }

            // 流写入
            InputStream ins = multipartFile.getInputStream();
            try {
                OutputStream os = new FileOutputStream(absoluteFilePath);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            ins.close();

        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        log.debug("视频暂存成功！路径：{}",absoluteFilePath);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        log.info("OssClient实例创建成功！");

        PutObjectResult putVideoRequestResult=null;
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putVideoRequest = new PutObjectRequest(bucketName, videoName, new File(absoluteFilePath));
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            putVideoRequestResult  = ossClient.putObject(putVideoRequest);

            String coverPath = VideoUtil.getVideoPicture(absoluteFilePath, currentClassPath + "tmp/cslp_oss/");
            log.debug("coverPath:{}",coverPath);
            //准备上传封面
            coverName=COVER_FILEPATH+ coverPath.substring(coverPath.lastIndexOf("/"));
            log.debug("coverName:{}",coverName);
            PutObjectRequest putCoverRequest = new PutObjectRequest(bucketName, coverName, new File(coverPath));
            PutObjectResult putCoverRequestResult = ossClient.putObject(putCoverRequest);

//            if(putCoverRequestResult!=null){
//                File file = new File(videoCoverPath );
//                file.delete();
//            }




        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }


        log.info("课程视频上传Oss成功！即将删除本地临时存放视频文件...");
        //文件上传完成后删除本地视频临时文件
//
        FileUtils.cleanDirectory(new File(currentClassPath+"tmp/cslp_oss/"));

        log.info("临时文件删除成功！！！");
        log.info("即将插入新增课程信息...");
        //上传文件完成
        //向MySQL插入新增课程数据
        Course course=new Course();
        BeanUtils.copyProperties(courseDTO,course);
        //传入视频实际存储的URL地址
        String videoUrl=PRE_URL+"/video"+"/"+fileName;
        log.debug("viedoUrl:{}",videoUrl);
        course.setVideoUrl(videoUrl);
        //设置上传时间
        course.setUploadTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        course.setReviewTime("0000-00-00 00:00:00");
        //设置文件类型
        course.setCourseType(suffix);
        //
        String coverUrl=PRE_URL+"/cover"+"/"+coverName;
        course.setCoverImage(coverUrl);
        iCourseService.addNew(course);
        log.info("新增课程信息成功！！！");
    }
}
